package com.hxd.otc.module.my.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.common.ApiConstants;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.my.bean.GoogleCreateBean;
import com.hxd.otc.module.my.contract.BindGoogleCodeContract;
import com.hxd.otc.module.my.presenter.BindGoogleCodePresenter;
import com.hxd.otc.utils.AddressUtil;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.widget.TitleBar;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

public class BindGoogleCodeActivity extends BaseActivity<BindGoogleCodePresenter> implements BindGoogleCodeContract.IView {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.tv_google_secret_key)
    TextView mTvGoogleSecretKey;
    @BindView(R.id.et_google_code)
    EditText mEtGoogleCode;
    @BindView(R.id.et_phone_ver_code)
    EditText mEtPhoneVerCode;
    @BindView(R.id.tv_get_phone_ver_code)
    @NonNull
    TextView mTvGetPhoneVerCode;
    @BindView(R.id.tv_phone_ver_code_label)
    TextView tvPhoneVerCodeLabel;

    private Disposable mPhoneVerDisposable;
    private int type = 1;

    private Map<String, SoftReference<Bitmap>> mImageCache = new HashMap<String, SoftReference<Bitmap>>();

    @Override
    protected BindGoogleCodePresenter createPresenter() {
        return new BindGoogleCodePresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_google_code;
    }

    @Override
    protected void initData() {
        mPresenter.getGoogleCode();
    }

    @Override
    protected void initEvent() {
        mTitleBar.setOnTitleBarItemClickListener(new TitleBar.OnTitleBarItemClickListener() {
            @Override
            public void onBack(View v) {

            }

            @Override
            public void onRight(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(WebViewActivity.EXTRA_TITLE, getString(R.string.how_to_bind_google));
                bundle.putString(WebViewActivity.EXTRA_URL, ApiConstants.URL_OF_GOOGLE_CERTIFICATION);
                $startActivity(WebViewActivity.class, bundle);
            }
        });
    }


    @OnClick({R.id.fl_qr_code, R.id.tv_copy_secret_key, R.id.tv_get_phone_ver_code, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fl_qr_code:
                break;
            case R.id.tv_copy_secret_key:
                AddressUtil.copyAddress(getApplicationContext(), mTvGoogleSecretKey.getText().toString().trim(), ResourceUtil.getString(R.string.wallet_toast_address_copy_success));
                break;
            case R.id.tv_get_phone_ver_code:
                if (type == 1) {//手机验证码
                    mPresenter.getPhoneVerCode();
                } else {//邮箱验证码
                    mPresenter.sendEmailVerCode();
                }
                break;
            case R.id.tv_confirm:
                mPresenter.bindGoogleCode(mEtGoogleCode.getText().toString().trim(), mTvGoogleSecretKey.getText().toString().trim(), mEtPhoneVerCode.getText().toString());
                break;
        }
    }

    @Override
    public void startPhoneCountdown() {
        ViewGroup.LayoutParams layoutParams = mTvGetPhoneVerCode.getLayoutParams();
        layoutParams.width = mTvGetPhoneVerCode.getWidth();
        mTvGetPhoneVerCode.setLayoutParams(layoutParams);
        mTvGetPhoneVerCode.setEnabled(false);
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mPhoneVerDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (mTvGetPhoneVerCode == null) return;
                        mTvGetPhoneVerCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        if (mTvGetPhoneVerCode == null) return;
                        mTvGetPhoneVerCode.setEnabled(true);
                        mTvGetPhoneVerCode.setText(R.string.send_message_code);
                    }
                })
                .subscribe();
    }

    @Override
    public void getGoogleCodeSuccess(GoogleCreateBean googleCreateBean) {
        mTvGoogleSecretKey.setText(googleCreateBean.getSecret());
        mIvQrCode.setImageBitmap(getBitmapByString(googleCreateBean.getQrcodeContent()));
        type = googleCreateBean.getType();
        if (type == 2) {
            tvPhoneVerCodeLabel.setText(getString(R.string.your_email_ver_code));
            mEtPhoneVerCode.setHint(getString(R.string.please_input_email_ver_code));
        }
    }

    private Bitmap getBitmapByString(String qrcodeContent) {
        // 从缓存中取软引用的Bitmap对象
        SoftReference<Bitmap> softBitmap = mImageCache.get(qrcodeContent);
        // 判断是否存在软引用
        if (softBitmap == null) {
            return addBitmapToCache(qrcodeContent);
        } else {
            // 取出Bitmap对象，如果由于内存不足Bitmap被回收，将取得空
            Bitmap bitmap = softBitmap.get();
            if (bitmap == null) {
                return addBitmapToCache(qrcodeContent);
            } else {
                return bitmap;
            }

        }
    }

    public Bitmap addBitmapToCache(String str) {
        // 强引用的Bitmap对象
        Bitmap bitmap = CodeUtils.createImage(str, DensityUtil.dp2px(170), DensityUtil.dp2px(170), null);
        // 软引用的Bitmap对象
        SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap);
        // 添加该对象到Map中使其缓存
        mImageCache.put(str, softBitmap);
        return bitmap;
    }

    @Override
    public void getGoogleCodeFail(String errMessage) {
        showToast(errMessage);
    }

    @Override
    public void bindGoogleCodeSuccess() {
        UserHelper.updateGoogleAuth(true);
        finish();
    }

    @Override
    public void bindGoogleCodeFail(String errMessage) {
        showToast(errMessage);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPhoneVerDisposable != null)
            mPhoneVerDisposable.dispose();

        for (String key : mImageCache.keySet()) {
            SoftReference<Bitmap> softBitmap = mImageCache.get(key);
            if (softBitmap != null) {
                Bitmap bitmap = softBitmap.get();
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }
    }


    @Override
    protected void initView() {
    }


}
